use std::time::Duration;

use base_data::channel::{event::ChannelEvent, CommandMsg, OriginateMsg, OriginateWay};
use switch::sip2::{manage::listen_device, register::SipRegEvent};
use tokio::time;
use tools::global_defin::tokio_runtime::get_rt;
use tracing::{info, span, warn, Instrument};

fn main() {
	let rt = tools::global_defin::tokio_runtime::get_rt();
	let _rt_g = rt.enter();
	let _log = tools::global_defin::trace_log::init_tracing_log();

	listen_device(&business_create, &business_reg, |s| {
		Box::pin(business_get_passwd(s))
	});

	std::thread::park();
}

fn business_reg(event: SipRegEvent) {
	match event {
		SipRegEvent::RegistSuccess(ev) => tracing::info!("成功注册...{ev:?}"),
		SipRegEvent::RegistLoginOut(ev) => tracing::info!("登出操作...{ev:?}"),
		SipRegEvent::RegistFailure(ev) => tracing::info!("注册失败...{ev:?}"),
	}
}

fn business_create(mut channel: base_data::channel::Channel) {
	tracing::info!("成功开始一个呼叫...{channel:?}");
	let id = channel.id;
	let span = span!(tracing::Level::INFO, "business", id);
	get_rt().spawn(
		async move {
			//呼叫过来以后立即的操作....只做一次
			// let c = channel.send(CommandMsg::HangupChannel(channel.id, base_data::channel::HangupReason::NotGayWay));
			// info!("发送挂断消息:{c:?}");
			// let  now: Duration = get_now_duration();
			time::sleep(Duration::from_millis(10)).await;
			let c = channel.send(CommandMsg::AnswerCall(9999));
			let o = OriginateMsg::new(
				channel.id,
				"18179156299".to_owned(),
				"18179156296".to_owned(),
				"".to_owned(),
				OriginateWay::RegisterUser,
			);
			let _ = channel.send(CommandMsg::Originate(o));
			info!("发送接通消息:{c:?}");
			loop {
				match channel.recv().await {
					Ok(ChannelEvent::ChannelHangup(id, e)) => {
						info!("收到挂断事件:{id},,{e}");
						break;
					}
					Ok(ChannelEvent::ChannelAnswer(id)) => {
						info!("收到接通事件,,,id:{id}");
					}
					Err(e) => {
						warn!("接收数据出错...{e}");
					}
					Ok(s) => {
						info!("收到还未处理的消息:{s:?}");
					}
				}
			}
		}
		.instrument(span),
	);
}

async fn business_get_passwd(name: &str) -> Option<String> {
	match name {
		"admin" => Some("admin".to_string()),
		"18179156296" => Some("18179156296".to_string()),
		_ => None,
	}
}
